const express = require("express");
const router = express.Router();

const config = require("../../config/config");
const NavModel = require("../../model/navModel");
const { getUnix } = require("../../model/tools");

router.get("/", async (req, res) => {
    const result = await NavModel.find({});
    res.render("admin/nav/index.html", { list: result });
})

router.get("/add", async (req, res) => {
    res.render("admin/nav/add.html");
})

router.post("/doAdd", async (req, res) => {
    /*
    {
        title: '测试导航1',
        link: 'www.baidu.com',
        position: '2',
        is_open_new: '1',
        sort: '10',
        status: '1'
    }
    */
    try {
        const result = new NavModel(Object.assign(req.body, { add_time: getUnix() }));
        await result.save();
        res.render("admin/public/success.html", {
            "redirectUrl": `/${config.adminPath}/nav`,
            "message": "增加数据成功"
        });
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${config.adminPath}/nav`,
            "message": "增加数据失败"
        });
    }
})

router.get("/edit", async (req, res) => {
    // 获取要修改数据的id
    const id = req.query.id;
    const result = await NavModel.find({ "_id": id });
    if(result.length > 0) {
        res.render("admin/nav/edit.html", {
            list: result[0]
        });
    } else {
        res.redirect(`/${config.adminPath}/nav`);
    }
})

router.post("/doEdit", async (req, res) => {
    try {
        await NavModel.updateOne({ _id: req.body.id }, req.body);
        res.render("admin/public/success.html", {
            "redirectUrl": `/${config.adminPath}/nav`,
            "message": "修改数据成功"
        });
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${config.adminPath}/nav`,
            "message": "修改数据失败"
        });
    }
});

router.get("/delete", async (req, res) => {
    try {
        await NavModel.deleteOne({ _id: req.query.id });

        res.render("admin/public/success.html", {
            "redirectUrl": `/${config.adminPath}/nav`,
            "message": "删除数据成功"
        });
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${config.adminPath}/nav`,
            "message": "修改数据失败"
        });
    }
});

module.exports = router